'''
关于文档的问答应用
'''
# 加载文档
from langchain.llms import OpenAI
from langchain.document_loaders import TextLoader
import os
# 设置全集OPEN_API_KEY值
os.environ['OPENAI_API_KEY']="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"

loader = TextLoader('test.txt')
# 创建索引，目前最好且最受欢迎的索引是 VectorStore 索引
from langchain.indexes import VectorstoreIndexCreator
# 默认集成了OpenAI，
# please add an environment variable `OPENAI_API_KEY` which contains it,
# or pass `openai_api_key` as a named parameter. (type=value_error)
index = VectorstoreIndexCreator().from_loaders([loader])

# 查询索引 方式一
query = "美丽的鲜花是什么？"
print(index.query(query))

# 查询索引 方式二
query = "What did the president say about Ketanji Brown Jackson"
index.query_with_sources(query)

# 问答涉及获取多个文档，然后对它们进行提问
from langchain.chains.question_answering import load_qa_chain
chain = load_qa_chain(llm, chain_type="stuff")
chain.run(input_documents=docs, question=query)

# 添加来源，语言模型还会引用它使用的来源（例如传递给它的文档之一）
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
chain({"input_documents": docs, "question": query}, return_only_outputs=True)